package com.cloud.observer;

import com.cloud.observer.annotation.ScheduledObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;
import java.util.UUID;

/**
 * @author: create by God of SJF
 * @version: v1.0
 * @description: com.cloud.observer
 * @date:2021/1/12
 */
public class ScheduledObserverRefresher {

    @Autowired
    BaseScheduledObserver baseScheduledObserver;

    @Autowired
    ScheduledObserverWrapper scheduledObserverWrapper;

    @Autowired
    ApplicationContext applicationContext;


    public void refresh(ScheduledInfo info, Integer refreshFlag) {
        synchronized (info) {
            if (refreshFlag == 1) {
                info.setLastBegin(new Date());
            } else {
                String edition = UUID.randomUUID().toString().replaceAll("-", "");
                info.setLastEnd(new Date());
                info.setSuccessNum(info.getSuccessNum() + 1);
                info.setEdition(edition);
                info.setInit(0);
            }
            baseScheduledObserver.map.put(info.getName(), info);
        }
    }

    public void initOrRefresh(String key, ScheduledObserver ScheduledObserver, Scheduled Scheduled,Object re, Integer refreshFlag) throws Exception {
        ScheduledInfo info;
        if (baseScheduledObserver.map.get(key) != null) {
            info = baseScheduledObserver.map.get(key);
            info.setRemark(String.valueOf(re));
            this.refresh(info, refreshFlag);
        } else {
            String edition = UUID.randomUUID().toString().replaceAll("-", "");
            info = new ScheduledInfo();
            info.setName(key);
            info.setEdition(edition);
            info = scheduledObserverWrapper.build(info, ScheduledObserver, Scheduled);
            baseScheduledObserver.map.put(key, info);
        }
    }
}
